package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.ReportDao;
import com.itheima.health.service.ReportService;
import com.itheima.health.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author likepei
 * @Date 2020/2/21 10:52
 * @Version v1.0
 * @Description 图表的业务实现类
 */
@Service
@Slf4j
@Transactional
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportDao reportDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 根据开始时间和结束时间查询该时间段的新增会员数量
     * @Author: Liuweipeng
     * @Param:
     * @Return:
     */
    @Override
    public Map<String,Object> findMemberReportByDate(String[] dateArray) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

            if(dateArray[0] == null || "".equals(dateArray[0]) || dateArray[1] == null || "".equals(dateArray[1])) {
                throw new RuntimeException("请输入起始时间和结束时间后再进行查询");
            }
            Date date0 = sdf.parse(dateArray[0]);
            Date date1 = sdf.parse(dateArray[1]);
            //定义起始时间
            String startTime = null;
            //定义结束时间
            String endTime = null;

            if (date0.compareTo(date1) < 0){
                startTime = dateArray[0] + "-31";
                endTime = dateArray[1] + "-31";
            }else if(date0.compareTo(date1) == 0) {
                throw new RuntimeException("请选择正确时间段查询");
            } else if (date0.compareTo(date1) > 0){
                startTime = dateArray[1] + "-31";
                endTime = dateArray[0] + "-31";
            }

            String[] startTimes = startTime.split("-");
            String[] endTimes = endTime.split("-");
            //相差月份
            int monthNumber = (Integer.valueOf(endTimes[0]) - Integer.valueOf(startTimes[0])) * 12 + (Integer.valueOf(endTimes[1]) - Integer.valueOf(startTimes[1]));

            List<String> months = new ArrayList<>();
            List<Integer> memberCount = new ArrayList<>();
            //获取
            Calendar calendar = Calendar.getInstance();
            Date endDate = sdf.parse(endTime);
            calendar.setTime(endDate);
            calendar.add(Calendar.MONTH,-monthNumber);

            for (int i = 0; i <= monthNumber; i++) {

                String month = sdf.format(calendar.getTime()) + "-31";
                Integer memberCountBeforeDate = reportDao.findMemberCountBeforeDate(month);
                months.add(sdf.format(calendar.getTime()));
                memberCount.add(memberCountBeforeDate);
                calendar.add(Calendar.MONTH,1);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("months",months);
            map.put("memberCount",memberCount);
            return map;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取指定月份列表的 会员数量
     *
     * @param monthList
     * @return
     */
    @Override
    public List<Integer> findMemberCountByMonth(List<String> monthList) {
        List<Integer> memberCount = new ArrayList<>();

        //遍历获取到 每一个月份
        for (String month : monthList) {
            // month ===>  2020.04
            month = month + ".31"; // 拼接后的日期 格式            2020.04.31

            //调用dao, 得到指定月份的会员累计数量
            Integer count = reportDao.findMemberCountBeforeDate(month);
            memberCount.add(count);
        }

        return memberCount;
    }

    /**
     * 套餐占比数据
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return reportDao.findSetmealCount();
    }

    /**
     * 各个年龄段的占比
     * @return
     */
    @Override
    public List<Map<String, Object>> getMemberAge() {
        List<Map<String, Object>>ageMapList = reportDao.getMemberAge();
        List<Map<String, Object>> memberAges = getMemberAges(ageMapList);
        return memberAges;
    }

    /**
     * 封装会员的年龄段
     * @param ageMapList
     * @return
     */
    public List<Map<String, Object>> getMemberAges(List<Map<String, Object>> ageMapList){
        List<Map<String, Object>> mapList = new ArrayList<>();
        int[] ages = new int[5];
        if (ageMapList != null){
            for (Map<String, Object> ageMap : ageMapList) {
                Object age = ageMap.get("age");
                Long value = (Long) ageMap.get("value");
                if (age != null) {
                    Long Age  = (Long) age;
                    if (Age > 45){
                        ages[0] += value;
                    }else if (Age > 30){
                        ages[1] += value;
                    }else if (Age > 18){
                        ages[2] += value;
                    } else {
                        ages[3] += value;
                    }
                }
            }

            String[] ageGroup = {"45岁以上","30-45岁","18-30岁","0-18岁","未知年龄"};
            for (int i = 0; i < ages.length; i++) {
                if (ages[i] != 0){
                    for (int j = 0; j <= 4; j++) {
                        if (i == j){
                            Map map = new HashMap();
                            map.put("name",ageGroup[j]);
                            map.put("value",ages[i]);
                            mapList.add(map);
                        }
                    }
                }
            }
            return mapList;
        }
        return null;
    }

    /**
     * 得到男女会员的占比数据
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findMemberSexCount() {
        List<Map<String, Object>> list = reportDao.getMemberSex();
        List<Map<String, Object>> memberSexs = getMemberSexs(list);

        return memberSexs;
    }

    /**
     * 整合性别数据 把1和2 换成男和女
     *
     * @param members
     * @return
     */
    public List<Map<String, Object>> getMemberSexs(List<Map<String, Object>> members) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (members != null) {
            for (Map<String, Object> member : members) {
                 Map map = new HashMap();
                String name = (String) member.get("name");
                Long value = (Long) member.get("value");
                if (name != null) {
                    if (name.equals("2")) {
                        name = "女";
                    } else{
                        name = "男";
                    }
                } else {
                    name = "未知";
                }
                map.put("name", name);
                map.put("value", value);
                list.add(map);
            }
        return list;
        }
        return  null;
    }

    /**
     * 获取运营统计数据
     * Map数据格式：
     * reportDate -> String 				// 报表日期
     * todayNewMember -> Integer			// 今日新增会员
     * thisWeekNewMember -> Integer		// 本周新增会员
     * thisMonthNewMember -> Integer		// 本月新增会员
     * totalMember -> Integer		    	// 总会员
     * todayOrderNumber -> Integer			// 今日预约人数
     * thisWeekOrderNumber -> Integer		// 本周预约人数
     * thisMonthOrderNumber -> Integer		// 本月预约人数
     * todayVisitsNumber -> Integer		// 今日到诊人数
     * thisWeekVisitsNumber -> Integer		// 本周到诊人数
     * thisMonthVisitsNumber -> Integer	// 本月到诊人数
     * hotSetmeal -> List<Map<String,Object>>	// 热门套餐
     *
     * @return
     */
    @Override
    public Map<String, Object> getBusinessReportData() {
        try {
            //获得今天日期
            //String today = "2020-02-22";
            String today = DateUtils.parseDate2String(DateUtils.getToday());
            //获得本周第一天日期(周一)
            //String thisWeekMonday = "2020-02-17";
            String thisWeekMonday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday());

            //获得本月第一天日期
            //String thisMonthFirst = "2020-02-01";
            String thisMonthFirst = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());

            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>today = " + today);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>thisWeekMonday = " + thisWeekMonday);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>thisMonthFirst = " + thisMonthFirst);

            //获取与会员有关数据 (今日、本周、本月、总人数)
            Integer todayNewMember = memberDao.findMemberCountByDate(today);
            Integer thisWeekNewMember = memberDao.findMemberCountAfterDate(thisWeekMonday);
            Integer thisMonthNewMember = memberDao.findMemberCountAfterDate(thisMonthFirst);
            Integer totalMember = memberDao.findMemberTotalCount();

            //获取与预约有关数据 (今日、本周、本月)
            Integer todayOrderNumber = orderDao.findOrderCountByDate(today);
            Integer thisWeekOrderNumber = orderDao.findOrderCountByAfterDate(thisWeekMonday);
            Integer thisMonthOrderNumber = orderDao.findOrderCountByAfterDate(thisMonthFirst);

            //获得到诊相关数据 (今日、本周、本月)
            Integer todayVisitsNumber = orderDao.findVisitsCountByDate(today);
            Integer thisWeekVisitsNumber = orderDao.findVisitsCountByAfterDate(thisWeekMonday);
            Integer thisMonthVisitsNumber = orderDao.findVisitsCountByAfterDate(thisMonthFirst);

            //获得套餐热门数据
            List<Map> hotSetmeal = orderDao.findHotSetmeal();

            //封装数据到map集合
            Map<String, Object> resultMap = new HashMap<>();
            //封装报表日期
            resultMap.put("reportDate", today);
            //会员有关数据 (今日、本周、本月、总人数)
            resultMap.put("todayNewMember", todayNewMember);
            resultMap.put("thisWeekNewMember", thisWeekNewMember);
            resultMap.put("thisMonthNewMember", thisMonthNewMember);
            resultMap.put("totalMember", totalMember);
            //获取与预约有关数据 (今日、本周、本月)
            resultMap.put("todayOrderNumber", todayOrderNumber);
            resultMap.put("thisWeekOrderNumber", thisWeekOrderNumber);
            resultMap.put("thisMonthOrderNumber", thisMonthOrderNumber);
            //到诊相关数据 (今日、本周、本月)
            resultMap.put("todayVisitsNumber", todayVisitsNumber);
            resultMap.put("thisWeekVisitsNumber", thisWeekVisitsNumber);
            resultMap.put("thisMonthVisitsNumber", thisMonthVisitsNumber);
            //套餐热门数据
            resultMap.put("hotSetmeal", hotSetmeal);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
